package com.bootdo.api.textUtil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.bootdo.api.domain.OfflineBody;
import com.bootdo.api.domain.OfflineHead;

public class FileUtil {
	// 复制文件夹
	public static void copyDirectiory(String sourceDir, String targetDir, boolean contantSub) throws IOException {
		// 新建目标目录
		(new File(targetDir)).mkdirs();

		// 获取源文件夹当前下的文件或目录
		File[] file = (new File(sourceDir)).listFiles();
		for (int i = 0; i < file.length; i++) {
			if (file[i].isFile()) {
				// 源文件
				File sourceFile = file[i];
				// 目标文件
				File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
				copyFile(sourceFile, targetFile);
			}
			if (file[i].isDirectory() && contantSub) {
				// 准备复制的源文件夹
				String dir1 = sourceDir + "/" + file[i].getName();
				// 准备复制的目标文件夹
				String dir2 = targetDir + "/" + file[i].getName();
				copyDirectiory(dir1, dir2, contantSub);
			}
		}
	}

	/**
	 * 
	 * @param srcFileName
	 * @param destFileName
	 * @param srcCoding
	 * @param destCoding
	 * @throws IOException
	 */
	public static void copyFile(File srcFileName, File destFileName, String srcCoding, String destCoding)
			throws IOException {// 把文件转换为GBK文件
		BufferedReader br = null;
		BufferedWriter bw = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(srcFileName), srcCoding));
			bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFileName), destCoding));
			char[] cbuf = new char[1024 * 5];
			int len = cbuf.length;
			int off = 0;
			int ret = 0;
			while ((ret = br.read(cbuf, off, len)) > 0) {
				off += ret;
				len -= ret;
			}
			bw.write(cbuf, 0, off);
			bw.flush();
		} finally {
			if (br != null)
				br.close();
			if (bw != null)
				bw.close();
		}
	}

	/**
	 * 
	 * @param filepath
	 * @throws IOException
	 */
	public static void del(String filepath) throws IOException {
		File f = new File(filepath);// 定义文件路径
		if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
			if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
				f.delete();
			} else {// 若有则把文件放进数组，并判断是否有下级目录
				File delFile[] = f.listFiles();
				int i = f.listFiles().length;
				for (int j = 0; j < i; j++) {
					if (delFile[j].isDirectory()) {
						del(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
					}
					delFile[j].delete();// 删除文件
				}
			}
		}
	}

	// 复制文件
	public static void copyFile(FileInputStream sourceFile, FileOutputStream targetFile) throws IOException {
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff = null;
		try {
			// 新建文件输入流并对它进行缓冲
			inBuff = new BufferedInputStream(sourceFile);

			// 新建文件输出流并对它进行缓冲
			outBuff = new BufferedOutputStream(targetFile);

			// 缓冲数组
			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();
		} finally {
			// 关闭流
			if (inBuff != null)
				inBuff.close();
			if (outBuff != null)
				outBuff.close();
		}
	}

	// 复制文件
	public static void copyFile(File sourceFile, File targetFile) throws IOException {
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff = null;
		try {
			// 新建文件输入流并对它进行缓冲
			inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

			// 新建文件输出流并对它进行缓冲
			outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

			// 缓冲数组
			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();
		} finally {
			// 关闭流
			if (inBuff != null)
				inBuff.close();
			if (outBuff != null)
				outBuff.close();
		}
	}

	/**
	 * 写入文件
	 * 
	 * @param path
	 *            文件路径
	 * @param fileName
	 *            文件名称
	 * @param content
	 *            写入内容
	 * @throws IOException
	 */
	public static void writeFile(String path, String fileName, OfflineHead head, OfflineBody body, String charter) throws IOException {
		//String special = "00011031001789295164          0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000FFFFFFFFFFFF2018032008162710160019          000099926800060000000000000000000000000000000152399000000000\r\n";
		FileOutputStream fos = null;
		File uploadPathFile = new File(path);
		String content = "";
		// 判断是否是目录，是则创建文件夹
		if (!uploadPathFile.exists()) {
			uploadPathFile.mkdirs();
		}
		File file = new File(path + fileName);
		byte bytes[] = new byte[1024];
		
		try {
			if (file.exists()) {
				content = body.toString();
				bytes = content.getBytes(charter);
				fos = new FileOutputStream(file, true);
				fos.write(bytes);
			} else {
				content = head.toString() + body.toString();
				bytes = content.getBytes(charter);
				fos = new FileOutputStream(file);
				fos.write(bytes);
			}
		} finally {
			if (fos != null) {
				fos.close();
			}
		}
	}

	/*public static String uploadFile(HttpServletRequest request, MultipartFile file, boolean compress) {
		
		 * //浏览器访问地址 String httpPath = Config.getDomain();
		 
		String folderName = "/image/upload";
		String path = null;
		try {
			// 服务器存放地址
			String basePath = request.getServletContext().getRealPath(folderName);
			// 如果文件夹不存在，就创建文件夹
			File dir = new File(basePath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// 后缀名
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1)
					.toLowerCase();
			// 文件名
			String fileName = System.currentTimeMillis() + "." + suffix;
			// 服务器上的相对路径
			 path = httpPath + folderName + "/" + fileName; 

			File dest = new File(basePath + "\\" + fileName);
			// 将本地文件保存到服务器dest
			file.transferTo(dest);

		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return path;
	}*/

	/**
	 * 上传单个文件
	 * 
	 * @param files
	 *            文件
	 * @param filenames
	 *            文件名后
	 * @param path
	 *            文件存放路径
	 * @return String 保存的文件名
	 */
	@SuppressWarnings("unused")
	public static String fileUpload(InputStream stream, String filenames, String path) {
		FileOutputStream fs = null;
		if (stream != null && StringUtils.isNotBlank(filenames)) {
			StringBuffer filename = new StringBuffer();
			// 获取文件后缀名
			String ext = filenames.substring(filenames.lastIndexOf('.'));

			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssssss");
			// 拼接文件名 时间撮+四位随机数
			filename.append(simpleDateFormat.format(new Date())).append(1234).append(ext);// StringHelper.getRandomNum(4)

			// 本地绝对路径
			File saveFile = new File(path);
			// 父文件夹不存在则创建文件夹
			if (!saveFile.exists() && !saveFile.isDirectory()) {
				saveFile.mkdirs();
			}

			try {
				fs = new FileOutputStream(path + "/" + filename);
				byte[] buffer = new byte[1024 * 1024];
				int bytesum = 0;
				int byteread = 0;
				while ((byteread = stream.read(buffer)) != -1) {
					bytesum += byteread;
					fs.write(buffer, 0, byteread);
					fs.flush();
				}

			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				// 关闭流
				try {
					fs.close();
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return filename.toString();
		}
		return null;
	}
}
